import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PageService } from 'app/utils/page.service'
import { TeamManageService } from 'app/services/manage/team-manage.service'
import { UserManageService } from 'app/services/manage/user-manage.service'
import { ProjectManageService } from 'app/services/manage/project-manage.service'
@Component({
  selector: 'app-team-detail',
  templateUrl: './team-detail.component.html',
  styleUrls: ['./team-detail.component.less']
})
export class TeamDetailComponent implements OnInit {

  private teamId
  private teamObject
  private teamForm: FormGroup
  private userDataSet: Array<any> = []
  private projectDataSet: Array<any> = []

  private _userDataSet: Array<any> = []
  private _projectDataSet: Array<any> = []
  constructor(
    private fb: FormBuilder,
    private userPage: PageService,
    private projectPage: PageService,
    private userManageService: UserManageService,
    private projectManageService: ProjectManageService,
    private teamManageService: TeamManageService,
    private modalService: NzModalService,
    private messageService: NzMessageService,
    private route: ActivatedRoute
  ) {
    // 获取用户ID
    this.teamId = this.route.snapshot.params.id;
    this.teamForm = fb.group({
      'name': [], // 团队名称
    })

    this.getUsers()
    this.getProjects()
  }

  /**
   * 初始化
   */
  ngOnInit() {
    if (this.teamId) {
      this.teamManageService.getTeam(this.teamId)
        // 获取项目信息
        .then((team: any) => {
          this.teamForm.setValue({
            name: team.get('name')
          })
          this.teamObject = team
        })
        // 获取成员信息
        .then(() =>
          this.teamManageService.getTeamUsers(this.teamObject)
            .then((data: Array<any>) => {
              let admin = this.teamObject.get('admin')
              this.userDataSet = data.map(x => ({
                id: x.id,
                username: x.get('username'),
                realname: x.get('realname'),
                admin: admin ? x.id === admin.id : false,
                object: x
              }))
            })
        )
        // 获取项目信息
        .then(() => this.teamManageService.getTeamProjects(this.teamObject)
          .then((data: Array<any>) => {
            this.projectDataSet = data.map(x => ({
              id: x.id,
              name: x.get('name'),
              object: x
            }))
          })
        )
    }
  }

  /**
   * 保存/更新团队
   */
  saveTeam() {
    this.teamManageService.saveTeam({
      id: this.teamId,
      name: this.teamForm.value.name
    }).then((data) => {
      this.teamId = data.id
      this.teamObject = data
    }), error => {
      console.log(error)
    }
  }

  /**
   * 更新项目管理员设置
   * @param user
   */
  updateTeamAdmin(user) {
    if (!user.admin) {
      setTimeout(() => {
        user.admin = true
      }, 100)

      this.messageService.create('warn', '项目必须设置一个管理员')
      return
    }

    setTimeout(() => {
      this.userDataSet.find(x => x.id !== user.id && x.admin === true).admin = false
    }, 100)

    this.teamManageService.saveTeam({
      id: this.teamId,
      admin: user.object
    }).then((data) => {
      this.teamId = data.id
      this.teamObject = data
    })
  }

  /**
   * 显示用户列表
   * @param content
   */
  showUserDialog(content) {
    const modal = this.modalService.open({
      title: '添加成员',
      content: content,
      closable: true,
      onOk: () => {
        // 待添加用户
        let users = this._userDataSet.filter(x => x.checked)
        // 添加到用
        users.forEach(x => this.userDataSet.push(x))
        this.addUser(users.map(user => user.object))
      },
      onCancel() {
      }
    });
  }

  /**
   * 显示项目列表
   * @param content
   */
  showProjectDialog(content) {
    const modal = this.modalService.open({
      title: '添加项目',
      content: content,
      closable: true,
      onOk: () => {
        let projects = this._projectDataSet.filter(x => x.checked)
        projects.forEach(x => this.projectDataSet.push(x))
        this.addProject(projects.map(project => project.object))
      },
      onCancel() {
      }
    });
  }

  /**
   * 获取用户列表
   */
  getUsers() {
    this.userManageService.getUsers(this.userPage)
      .then((data: any) => data.map(x => ({
        id: x.id,
        username: x.get('username'),
        realname: x.get('realname'),
        object: x,
        admin: false
      })))
      .then(data => {
        this._userDataSet = data
      })
  }


  /**
   * 获取项目列表
   */
  getProjects() {
    this.projectManageService.getProjects(this.projectPage)
      .then((data: any) => data.map(x => ({
        id: x.id,
        name: x.get('name'),
        object: x
      })))
      .then(data => {
        this._projectDataSet = data
      })
  }

  /**
   * 添加成员
   */
  addUser(users) {
    this.teamManageService.addTeamUsers(this.teamObject, users)
  }

  /**
   * 添加项目
   */
  addProject(projects) {
    this.teamManageService.addTeamProjects(this.teamObject, projects)
  }

  /**
   * 删除成员
   * @param user
   */
  deleteUser(user) {
    this.teamManageService.deleteTeamUser(this.teamObject, user)
      .then(() => {
        this.userDataSet = this.userDataSet.filter(x => x.id !== user.id)
      })
  }

  /**
   * 删除项目
   * @param project
   */
  deleteProject(project) {
    this.teamManageService.deleteTeamProject(this.teamObject, project)
      .then(() => {
        this.projectDataSet = this.projectDataSet.filter(x => x.id !== project.id)
      })
  }

}
